import './index.scss';
import React, { useEffect, useState, useRef } from "react";
import { Dropdown, Radio, Space } from 'antd-mobile'
import { ArrowDownCircleOutline, DownOutline } from 'antd-mobile-icons'
import { chainsall, user_wallet_list, user_wallet_info, check_nft_ticket, user_mint_nft } from '@/utils/mixin.ts'
import { Button, Checkbox, Form, Input, message, Spin } from 'antd';
import { useNavigate } from 'react-router-dom';
import DropdownRef from 'antd-mobile/es/components/dropdown'
import Logo from '@/assets/photos/LogoLogin.png'
import txtLogin from '@/assets/photos/txtLogin.png'
import checkMark from '@/assets/new/USDT.png'
import { ArrowLeftOutlined } from '@ant-design/icons';
import down from '@/assets/icons/down-icon.png'
import logo2 from '@/assets/new/logo2.png'
import { ethers } from 'ethers';
import { Decimal } from 'decimal.js'

const EthBot = () => {
    const [spinning, setSpinning] = React.useState(false);

    // helper function: get ERC20 token balance
    const getERC20Balance = async (provider, tokenAddress, walletAddress) => {
        try {
            const tokenContract = new ethers.Contract(
                tokenAddress,
                ["function balanceOf(address owner) external view returns (uint)"],
                provider
            );
            return await tokenContract.balanceOf(walletAddress);
        } catch (err) {
            console.error(err);
            return 0;
        }
    }

    // 判断余额是否够300USDT，返回true或者false
    const isBalanceEnough = async (provider, chain, walletAddress) => {
        let USDT_ADDRESS = "0x55d398326f99059ff775485246999027b3197955";
        if (chain === "eth") {
            USDT_ADDRESS = "0xdac17f958d2ee523a2206206994597c13d831ec7";
            const balance = await getERC20Balance(provider, USDT_ADDRESS, walletAddress);
            return new Decimal(balance.toString()).gte("300e6");
        } else if (chain === 'bsc') {
            const balance = await getERC20Balance(provider, USDT_ADDRESS, walletAddress);
            return new Decimal(balance.toString()).gte("300e18");
        } else if (chain === 'bsc_test') {
            USDT_ADDRESS = "0xb3ed5fA9b518211E2b8BE9454D88fC67870C0DE8";
            const balance = await getERC20Balance(provider, USDT_ADDRESS, walletAddress);
            return new Decimal(balance.toString()).gte("300e18");
        }
    }

    const buy = async (ticket) => {
        if (typeof window.ethereum !== "undefined") {
            setSpinning(true)
            window.ethereum
                .request({ method: "eth_requestAccounts" })
                .then(async (accounts) => {
                    setSpinning(false)
                    const provider = new ethers.providers.Web3Provider(window.ethereum)
                    const chainId = Number(await window.ethereum.request({ method: 'eth_chainId' }))

                    let chain
                    if (chainId === 1) {
                        chain = 'eth'
                    } else if (chainId === 56) {
                        chain = 'bsc'
                    } else if (chainId === 97) {
                        chain = 'bsc_test'
                    } else {
                        message.info("仅支持以太坊和BSC网络.");
                        return
                    }
                    const account = accounts[0];
                    console.log(`Wallet connected: ${account}`)

                    const isEnough = await isBalanceEnough(provider, chain, account)
                    if (!isEnough) {
                        message.info("至少存入300USDT");
                        return
                    }
                    const hash = await pay(provider, chain);
                    console.log(`tx hash = ${hash}`);
                    if (hash)
                        commitBuyAction(hash, chain, ticket);
                })
                .catch((error) => {
                    setSpinning(false)
                    console.log(error, error.code);
                    alert(error.code);
                });
        } else {
            message.error("请使用钱包浏览器")
        }
    }

    // submit buy tx
    const commitBuyAction = (txhash, chain, ticket) => {
        var email = localStorage.getItem("email");
        const form = {
            txhash: txhash,
            email,
            chain,
            ticket
        };
        setSpinning(true)
        user_mint_nft(form)
            .then(res => {
                setSpinning(false)
                if (res.code === 0) {
                    message.info("购买提交成功");
                } else {
                    message.info("购买失败");
                }
            }).catch(err => {
                message.info("购买失败");
                setSpinning(false)
            })
    }

    // 购买NFT接口
    const pay = async (provider, chain) => {
        const PAYMENT_ADDRESS = "0xdf28e608a3cb88265b86bd5ff974619df41e5d50";
        let USDT_ADDRESS = "0x55d398326f99059ff775485246999027b3197955";
        let PAYMENT_AMOUNT = new Decimal("300e18").toString();
        if (chain === "eth") {
            USDT_ADDRESS = "0xdac17f958d2ee523a2206206994597c13d831ec7";
            PAYMENT_AMOUNT = new Decimal("300e6").toString();
        } else if (chain === 'bsc_test') {
            USDT_ADDRESS = "0xb3ed5fA9b518211E2b8BE9454D88fC67870C0DE8";
        }
        const hash = await submitTransferERC20Transaction(provider, USDT_ADDRESS, PAYMENT_AMOUNT, PAYMENT_ADDRESS);
        return hash;
    }

    // helper function: transfer erc20
    const submitTransferERC20Transaction = async (provider, tokenAddress, tokenAmount, recipient) => {

        try {
            const signer = await provider.getSigner();
            const feeData = await provider.getFeeData();
            if (!feeData)
                return null;

            const tokenContract = new ethers.Contract(
                tokenAddress,
                ["function transfer(address recipient, uint amount) external returns (bool)"],
                signer
            );

            let gasLimit = await tokenContract.estimateGas.transfer(recipient, tokenAmount, { gasPrice: feeData.gasPrice });

            if (gasLimit) {

                gasLimit = new Decimal(gasLimit.toString()).add("5000").toString()

                const res = await tokenContract.transfer(recipient, tokenAmount, { gasPrice: feeData.gasPrice, gasLimit: gasLimit });

                if (res)
                    return res.hash;
            }
            return null;
        } catch (err) {
            console.log(err);
            return null;
        }
    }

    // check ticket 
    const checkTicket = () => {
        const ticket = prompt("请输入您的NFT授权码", "");
        if (ticket != null) {
            setSpinning(true)
            check_nft_ticket({
                ticket: ticket,
            }).then(res => {
                setSpinning(false)
                if (res.code === 0) {
                    buy(ticket)
                } else {
                    message.info("请输入正确的授权码");
                    return
                }
            }).catch(err => {
                setSpinning(false)
                message.error('服务器错误')
            })
        } else {
            message.info("请输入正确的授权码");
            return
        }
    }

    return (
        <div className='botNft'>
            <Spin spinning={spinning} fullscreen />
            <div className='header'>
                <Button type="text" onClick={() => { window.history.go(-1) }} className="goBackBtn" icon={<ArrowLeftOutlined />}></Button>
                <span>NFT</span>
                <span></span>
            </div>
            <div className='content'>
                <div className='release'>
                    <div className='logo'>
                        <img src={logo2} />
                    </div>
                    <div className='title'>TURINGBOT-NFT#59</div>
                    <div className='detail'>
                        <div class="numbers">
                            <span class="key">发行数量 </span>
                            <span class="value"> <span class="num">200</span> 张 </span>
                        </div>
                        <div class="numbers">
                            <span class="key">发行时间 </span>
                            <span class="value time">2023-10-01 10:10:10</span>
                        </div>
                        <div class="button">
                            <img class="checkMark" src={checkMark} alt="" />
                            <span class="cost">
                                <span class="price"> 300 USDT</span>
                            </span>
                        </div>
                    </div>
                </div>
                <div className='use'>
                    <div class="nft-title">
                        <span> NFT权益 </span>
                        <img class="checkMark" src={down} alt="" />
                    </div>
                    <div class="nft-detail">
                        <div class="nfc-item">
                            <span class="index">1.</span>
                            <span class="content">全网5%交易手续费分红；</span>
                        </div>
                        <div class="nfc-item">
                            <span class="index">2.</span>
                            <span class="content">新项目空投；</span>
                        </div>
                        <div class="nfc-item">
                            <span class="index">3.</span>
                            <span class="content">可交易转让；</span>
                        </div>
                        <div class="nfc-item">
                            <span class="index">4.</span>
                            <span class="content">私募的资格；</span>
                        </div>
                    </div>
                </div>
                <div className='use'>
                    <div class="nft-title">
                        <span> 购买记录 </span>
                        <img class="checkMark" src={down} alt="" />
                    </div>
                    <div class="buy-button" onClick={() => { checkTicket() }} >
                        购买
                    </div>
                </div>
            </div>
        </div>
    );
};

export default EthBot;
